<?php

class CSVDataParser extends DataParser {

    public function parseData($data) {
        $group = $this->getOption('group');
        $name = $this->getOption('name');
        $groupname = $this->getOption('groupname');
        $str = str_replace("\"\n", "\"\r", $data);
        $arr = str_getcsv($str, "\r", "'"); // 5.3.3 Bug?
        $fields = str_getcsv($arr[0]);
        $groups = array();
        foreach ($arr as $i => $item) {
            if ($i != 0) {
                $arrs = str_getcsv($item);
                foreach ($fields as $j => $field) {
                    $detail[$field] =  $arrs[$j];
                }
                if (isset($group) && !in_array($detail[$group], $groups)) {
                    $groups[] = $detail[$group];
                }
                if (isset($groupname)) {
                    if ($detail[$group] == $groupname) {
                        $array[] = $detail;
                    }
                } else {
                    $array[] = $detail;
                }
            }
        }
        $groupArrs = array();
        if ($group != "" && $groupname == "") {
            foreach ($groups as $item) {
                $groupArr[$name] = $item;
                $groupArrs[] = $groupArr;
            }
            $array = $groupArrs;
        }
        $this->setTotalItems(count($array));
        return $array;
    }
}
